/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { FeatureBaseCommand, FeaturedCmdDialogParams } from '@app-cad/types';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';

enum StiffenerMode {
  SOLID = 'solid',
  CYLINDER = 'cylinder',
}

type FormData = {
  mode: StiffenerMode;
  curve: pickedLineData;
  surface1: pickedFaceData;
  surface2: pickedFaceData;
  thick1?: number;
  thick2?: number;
  radius?: number;
};

type Params = {
  mode: StiffenerMode;
  curve: string;
  surface1: string;
  surface2: string;
  thick1?: number;
  thick2?: number;
  radius?: number;
};

function CommandStiffener({ title, onClose, props }: FeaturedCmdDialogParams) {
  const initData = {
    mode: StiffenerMode.SOLID,
    curve: null,
    surface1: null,
    surface2: null,
    thick1: 0,
    thick2: 0,
    radius: 0,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useEffect(() => {
    onPreview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { mode, curve, surface1, surface2, thick1, thick2, radius } = params;

    await initEditDependency([curve, surface1, surface2]);

    setFormData({
      mode: mode,
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      surface1: picker.generatePickObjByPickID(surface1) as pickedFaceData,
      surface2: picker.generatePickObjByPickID(surface2) as pickedFaceData,
      thick1: thick1 ?? 0,
      thick2: thick2 ?? 0,
      radius: radius ?? 0,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { mode, curve, surface1, surface2, thick1, thick2, radius } =
      formData;
    if (mode === StiffenerMode.SOLID) {
      return (
        curve != null &&
        surface1 != null &&
        surface2 != null &&
        (thick2 != 0 || thick1 != 0)
      );
    } else if (mode === StiffenerMode.CYLINDER) {
      return (
        curve != null && surface1 != null && surface2 != null && radius != 0
      );
    } else {
      return false;
    }
  };
  const finishValid = useMemo(isFormDataValid, [formData]);
  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-stiffener', {
      onClose,
      finishDraw: checkAndFinish,
      commandName: 'CreateStiffener',
      editDxid: props?.shape,
    });

  const onPreview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const execute = async (preview: boolean = false) => {
    const { mode, curve, surface1, surface2, thick1, thick2, radius } =
      formData;
    const params: Params =
      mode === StiffenerMode.SOLID
        ? {
            mode: mode,
            curve: getIdOfPickedObj(curve),
            surface1: getIdOfPickedObj(surface1),
            surface2: getIdOfPickedObj(surface2),
            thick1: Math.abs(thick1),
            thick2: Math.abs(thick2),
          }
        : {
            mode: mode,
            curve: getIdOfPickedObj(curve),
            surface1: getIdOfPickedObj(surface1),
            surface2: getIdOfPickedObj(surface2),
            radius: Math.abs(radius),
          };

    await confirmCommand(
      {
        a: params,
        p: preview,
      },
      preview,
    );
  };

  const schema = useMemo(() => {
    const modeSchema = {
      type: 'string',
      title: '模式',
      default: StiffenerMode.SOLID,
      oneOf: [
        {
          type: 'string',
          title: '三角形实体',
          const: StiffenerMode.SOLID,
        },
        {
          type: 'string',
          title: '圆柱',
          const: StiffenerMode.CYLINDER,
        },
      ],
    };

    if (formData.mode === StiffenerMode.SOLID) {
      return {
        properties: {
          mode: modeSchema,
          curve: {
            type: 'string',
            title: '目标草图轮廓',
            format: PickInputRJSFFormat.PickSketchCurve,
          },
          surface1: {
            type: 'string',
            title: '目标曲面1',
            format: PickInputRJSFFormat.PickSurface,
          },
          surface2: {
            type: 'string',
            title: '目标曲面2',
            format: PickInputRJSFFormat.PickSurface,
          },
          thick1: {
            type: 'number',
            title: '厚度1',
            default: 0,
            format: NumberInputFormat.Length,
            minimum: 0,
          },
          thick2: {
            type: 'number',
            title: '厚度2',
            default: 0,
            format: NumberInputFormat.Length,
            minimum: 0,
          },
        },
      };
    }

    if (formData.mode === StiffenerMode.CYLINDER) {
      return {
        properties: {
          mode: modeSchema,
          curve: {
            type: 'string',
            title: '目标草图轮廓',
            format: PickInputRJSFFormat.PickSketchCurve,
          },
          surface1: {
            type: 'string',
            title: '目标曲面1',
            format: PickInputRJSFFormat.PickSurface,
          },
          surface2: {
            type: 'string',
            title: '目标曲面2',
            format: PickInputRJSFFormat.PickSurface,
          },
          radius: {
            type: 'number',
            title: '半径',
            default: 0,
            minimum: 0,
            format: NumberInputFormat.Length,
          },
        },
      };
    }

    return schema;
  }, [formData.mode]);

  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入草图轮廓',
          'ui:autofocus': true,
        },
        surface1: {
          'ui:placeholder': '请输入曲面1',
        },
        surface2: {
          'ui:placeholder': '请输入曲面2',
        },
        thick1: {
          'ui:placeholder': '请输入厚度1',
        },
        thick2: {
          'ui:placeholder': '请输入厚度2',
        },
        radius: {
          'ui:placeholder': '请输入半径',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
      noValidate
    />
  );
}

export const cmdStiffener: FeatureBaseCommand = {
  id: 'CmdStiffener',
  label: 'command.stiffener',
  icon: 'commands/feature/stiffener',
  create: (label, onClose, props) => (
    <CommandStiffener
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
